package com.chd.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.chd.dto.Result;
import com.chd.entity.VoucherOrder;
import com.chd.mapper.VoucherOrderMapper;
import com.chd.service.ISeckillVoucherService;
import com.chd.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chd.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;

import static com.chd.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedissonClient redissonClient2;

    @Resource
    private RedissonClient redissonClient3;

    @Resource
    private RabbitTemplate rabbitTemplate;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
//        // 1. 查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        // 2. 判断秒杀是否在秒杀时段
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀尚未开始");
//        }
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已经结束");
//        }
//        // 3. 判断库存是否充足
//        if (voucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
        Long userId = UserHolder.getUser().getId();
//
////        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString());
        if (result != 0L) {
            return Result.fail(result == 1L ? "库存不足":"不能重复下单");
        }

        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = IdUtil.getSnowflake(WORKER_ID, DATA_CENTER_ID).nextId();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
//        save(voucherOrder);
        // 发送 订单创建命令 到 MQ
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT_VOUCHER,
                ROUTING_KEY_MAKE_VOUCHERORDER,
                JSONUtil.toJsonStr(voucherOrder));
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(0);
//
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//
//        if (!lock.tryLock()) {
//            return Result.fail("禁止重复下单");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
    }

    @RabbitListener(queues = MAKE_VOUCHER_CONSUMER)
    public void makeVoucherOrderConsumer(String msg) {
        VoucherOrder voucherOrder = JSONUtil.toBean(msg, VoucherOrder.class);

        Long userId = voucherOrder.getUserId();
        RLock lock1 = redissonClient.getLock("lock:order:" + userId);
        RLock lock2 = redissonClient2.getLock("lock:order:" + userId);
        RLock lock3 = redissonClient3.getLock("lock:order:" + userId);
        RLock lock = redissonClient.getMultiLock(lock1, lock2, lock3);
        boolean isLock = lock.tryLock();
        if (!isLock) return;
        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getId();
        Long voucherId = voucherOrder.getVoucherId();
        if (query().eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count() > 0) {
            return;
        }
        boolean success = seckillVoucherService
                .update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!success) {
            return;
        }
        save(voucherOrder);
    }
}
